package utils

import (
	"context"
	"encoding/json"
	"github.com/go-resty/resty/v2"
	"time"
)

// HTTPClient 封装 resty 客户端
type HTTPClient struct {
	client *resty.Client
}

// NewHTTPClient 创建一个新的 HTTP 客户端
func NewHTTPClient(timeout time.Duration, retryCount int, retryWaitTime time.Duration) *HTTPClient {
	client := resty.New().
		SetTimeout(timeout).
		SetRetryCount(retryCount).
		SetRetryWaitTime(retryWaitTime).
		SetRetryMaxWaitTime(timeout)

	return &HTTPClient{
		client: client,
	}
}

// SetBaseURL 设置基础 URL
func (c *HTTPClient) SetBaseURL(url string) *HTTPClient {
	c.client.SetBaseURL(url)
	return c
}

// SetHeader 设置请求头
func (c *HTTPClient) SetHeader(key, value string) *HTTPClient {
	c.client.SetHeader(key, value)
	return c
}

// SetHeaders 批量设置请求头
func (c *HTTPClient) SetHeaders(headers map[string]string) *HTTPClient {
	c.client.SetHeaders(headers)
	return c
}

// Get 发送 GET 请求
func (c *HTTPClient) Get(ctx context.Context, url string, params map[string]string) (*resty.Response, error) {
	return c.client.R().
		SetContext(ctx).
		SetQueryParams(params).
		Get(url)
}

// Post 发送 POST 请求
func (c *HTTPClient) Post(ctx context.Context, url string, body interface{}) (*resty.Response, error) {
	return c.client.R().
		SetContext(ctx).
		SetBody(body).
		Post(url)
}

// PostForm 发送 POST 表单请求
func (c *HTTPClient) PostForm(ctx context.Context, url string, data map[string]string) (*resty.Response, error) {
	return c.client.R().
		SetContext(ctx).
		SetFormData(data).
		Post(url)
}

// Put 发送 PUT 请求
func (c *HTTPClient) Put(ctx context.Context, url string, body interface{}) (*resty.Response, error) {
	return c.client.R().
		SetContext(ctx).
		SetBody(body).
		Put(url)
}

// Delete 发送 DELETE 请求
func (c *HTTPClient) Delete(ctx context.Context, url string) (*resty.Response, error) {
	return c.client.R().
		SetContext(ctx).
		Delete(url)
}

// GetJSON 发送 GET 请求并解析 JSON 响应
func (c *HTTPClient) GetJSON(ctx context.Context, url string, params map[string]string, result interface{}) error {
	resp, err := c.Get(ctx, url, params)
	if err != nil {
		return err
	}
	return json.Unmarshal(resp.Body(), result)
}

// PostJSON 发送 POST 请求并解析 JSON 响应
func (c *HTTPClient) PostJSON(ctx context.Context, url string, body interface{}, result interface{}) error {
	resp, err := c.Post(ctx, url, body)
	if err != nil {
		return err
	}
	return json.Unmarshal(resp.Body(), result)
}

// SetBasicAuth 设置基本认证
func (c *HTTPClient) SetBasicAuth(username, password string) *HTTPClient {
	c.client.SetBasicAuth(username, password)
	return c
}

// SetBearerToken 设置 Bearer Token
func (c *HTTPClient) SetBearerToken(token string) *HTTPClient {
	c.client.SetAuthToken(token)
	return c
}

// EnableDebug 启用调试模式
func (c *HTTPClient) EnableDebug() *HTTPClient {
	c.client.SetDebug(true)
	return c
}

// DisableDebug 禁用调试模式
func (c *HTTPClient) DisableDebug() *HTTPClient {
	c.client.SetDebug(false)
	return c
}
